/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.miit.elearning.vtutor.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import ru.miit.elearning.vtutor.data.DataMiner;

/**
 *
 * @author Cyclone
 */
public class UpdateConfigServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        DataMiner miner = null;
        try {
            String jsonText = request.getParameter("json");
            JSONArray arr = new JSONArray(jsonText);
            miner = new DataMiner();

            //int labId = Integer.parseInt(request.getParameter("labId"));
            int courseId = Integer.parseInt(request.getParameter("courseId"));
            int labNumber = Integer.parseInt(request.getParameter("labNumber"));

            Set<Integer> allKeysSet = miner.getCheckObjectsIdSet(courseId, labNumber);
            Set<Integer> liveKeysSet = new HashSet<Integer>();

            JSONArray responseArray = null;
            for (int i = 0; i < arr.length(); i++) {
                JSONObject coJSON = (JSONObject) arr.get(i);

                int id = coJSON.getInt("id");
                if (id >= 0) {
                    liveKeysSet.add(id);
                    miner.updateCheckObject(id, coJSON.getString("path"), coJSON.getInt("type"), coJSON.optJSONArray("combs"));
                } else {
                    if (responseArray == null) {
                        responseArray = new JSONArray();
                    }
                    int newId = miner.addCheckObject(courseId, labNumber, coJSON.getString("path"), coJSON.getInt("type"), coJSON.optJSONArray("combs"));
                    JSONObject idJSON = new JSONObject();
                    idJSON.put("tempId", id);
                    idJSON.put("newId", newId);
                    responseArray.put(idJSON);
                }

            }

            allKeysSet.removeAll(liveKeysSet);
            Set<Integer> deleteKeysSet = allKeysSet;
            for (Iterator<Integer> it = deleteKeysSet.iterator(); it.hasNext();) {
                Integer deleteId = it.next();
                miner.deleteCheckObject(deleteId);
            }

            if (responseArray != null) {
                out.print(responseArray);
            }

        } catch (JSONException ex) {
            ex.printStackTrace();
            Logger.getLogger(UpdateConfigServlet.class.getName()).log(Level.SEVERE, null, ex);

            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(UpdateConfigServlet.class.getName()).log(Level.SEVERE, null, ex);

            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            out.close();
            if (miner != null) {
                miner.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
